import json
from functools import wraps
from fastapi import Request
from core.storage import RedisStorage
from core.constants import TimeUnit, CacheConstants


def CacheAble(
    expires: int = 30,
    timeUnit: int = TimeUnit.SECONDS
):
    """
    接口数据缓存
    """
    def decorator(func):
        @wraps(func)
        async def wrapper(*args, **kwargs):
            req: Request = kwargs.get('req')
            combineKey: str = CacheConstants.API_CACHE_KEY + req.client.host + ':' + req.url.path.replace("/","_")
            data = await RedisStorage.get_cache_object(req.app, combineKey)
            # print(combineKey, data)
            if data is None:
                result = await func(*args, **kwargs)
                await RedisStorage.set_cache_object(req.app, combineKey, json.dumps(result), expires * timeUnit)
            else:
                result = json.loads(data)

            return result

        return wrapper

    return decorator
